package com.vinaprime.primeschedule.presentation;

import java.io.IOException;
import java.io.Serializable;
import java.text.ChoiceFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.vinaprime.primeschedule.businesslayer.VPSnoozeSound_BL;
import com.vinaprime.primeschedule.entities.VPSnoozeSound;

public class VpsnoozesoundListActivity extends Activity {

	public final static String SOUND_CHOOSE = "com.vinaprime.primeschedule.presentation.SOUND_CHOOSE";
	public final static int REQUEST_CODE = 1;
	
	private ApplicationInformation myAppInfo;
	private String myPath;
	
	private List<VPSnoozeSound> myListSound;
	private List<VPSnoozeSound> myListSoundFilter;
	private VPSnoozeSound_BL mySoundBL;
	
	private ListView myListView;
	private ListViewSnoozeSoundListAdapter myListAdapter;
	
	private TextView myTvFileName, myTvTimeLine;
	
	private ImageButton myIbtnPlay, myIbtnNext, myIbtnPrevious;
	
	private MediaPlayer myPlayer;
	private SeekBar mySeekBar;
	
	private Timer myTimer;
	
	private int myPositionseek;
	private int myPositionCurrentOfList;
	private int myDuration;
	private int myCurrent;
	
	//private boolean myRunning;  
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vpsnoozesound_list);
		getActionBar().hide();
		
		initialize();
		showlistview();
		
		myIbtnPlay.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onStartSound(myPositionCurrentOfList);
			}
		});
		
		myIbtnNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {

					onStopSound();
				} catch (Exception e) {			
					e.printStackTrace();
				};				
				
				int last = myListView.getLastVisiblePosition();
				
				if(myPositionCurrentOfList < last ){
					myPositionCurrentOfList = myPositionCurrentOfList +1;
					onStartSound(myPositionCurrentOfList);					
				}
				else{
					myPositionCurrentOfList = 0;
					onStartSound(myPositionCurrentOfList);
				}
				
				myListView.setItemChecked(myPositionCurrentOfList, true);
				
				myListAdapter.setMyLastSelectedPostition(myPositionCurrentOfList);
			}
		});
		
		myIbtnPrevious.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {					
					onStopSound();
				} catch (Exception e) {					
					e.printStackTrace();
				};		
				
				int last = myListView.getLastVisiblePosition();
				
				if (myPositionCurrentOfList > 0){					
					myPositionCurrentOfList = myPositionCurrentOfList-1;
					onStartSound(myPositionCurrentOfList);					
				}else{
					myPositionCurrentOfList = last;
					onStartSound(myPositionCurrentOfList);	
				}
				
				myListView.setItemChecked(myPositionCurrentOfList, true);
				
				myListAdapter.setMyLastSelectedPostition(myPositionCurrentOfList);
			}
		});
		
		mySeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				if(fromUser){  
					if (!myPlayer.isPlaying())
						onStartSound(myPositionCurrentOfList);					 
					myPlayer.seekTo(progress);  					
	            }
				
				UpdateTimeWhenPlay();
			}			
		});		
		myTimer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {				
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {						
						String str1, str2;
						str1 = myTvFileName.getText().toString().substring(1);
						str2= myTvFileName.getText().toString().substring(0, 1);
						myTvFileName.setText(str1 + str2);
						
						if (myPlayer.isPlaying()){							
								if(mySeekBar != null){
									mySeekBar.setProgress(myPlayer.getCurrentPosition());
								}
						}
					}
				});
			}
		}, 0, 1000);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.vpsnoozesound_list, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_cancel:
			finish();
			break;

		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	public void initialize(){
		/*Khoi tao du lieu, duong dan*/		
		myAppInfo = new ApplicationInformation(this);
		myPath = myAppInfo.getDBPath();
		mySoundBL = new VPSnoozeSound_BL(this, myPath + "databases/");
		
		myTimer = new Timer();
		
		myPositionseek = 0;
		myPositionCurrentOfList = 0;
		myDuration = 0;
		myCurrent = 0;	
		
		myTvFileName = (TextView)findViewById(R.id.tvfilename);
		myTvFileName.setText("VinaPrime  ");
		
		myTvTimeLine = (TextView)findViewById(R.id.tvtimeline);
		
		myPlayer = (MediaPlayer)getLastNonConfigurationInstance();
        
		//If not, make a new one
        if (myPlayer == null) {
        	myPlayer = new MediaPlayer();
        }
        
        myIbtnPlay = (ImageButton)findViewById(R.id.ibtnPlay);
        myIbtnNext = (ImageButton)findViewById(R.id.ibtnNext);
        myIbtnPrevious = (ImageButton)findViewById(R.id.ibtnPrevious);
        
        mySeekBar = (SeekBar)findViewById(R.id.songProgressBar);
	}
	
	private void UpdateTimeWhenPlay(){	
			myCurrent = myPlayer.getCurrentPosition();
			int cSecond = (int) (myCurrent/1000)%60;
			int cMinute = (int) ((myCurrent/1000)/60)%60;
			int cHour = (int) (((myCurrent/1000)/60)/60)%60;
			////
			int dSecond = (int) (myDuration/1000)%60;
			int dMinute = (int) ((myDuration/1000)/60)%60;
			int dHour = (int) (((myDuration/1000)/60)/60)%60;			
			if (dHour ==0 ){
				myTvTimeLine.setText(String.format("%02d:%02d/%02d:%02d", cMinute,cSecond,dMinute, dSecond));
			}else{
				myTvTimeLine.setText(String.format("%02d:%02d:%02d/%02d:%02d:%02d", cHour, cMinute, cSecond, dHour, dMinute, dSecond));
			}	

			String tmp1, tmp2;
			tmp1 = String.format("%02d:%02d", cMinute,cSecond);
			tmp2 = String.format("%02d:%02d",dMinute, dSecond);
			if(tmp1.equals(tmp2))
			{
				mySeekBar.setProgress(0);
				myIbtnPlay.setBackgroundResource(android.R.drawable.ic_media_play);
				
			}
	}

	public void showlistview(){
		myListSound = mySoundBL.getAllSoundActived();
		myListView = (ListView)findViewById(R.id.lvSnoozeSound);
		myListView.setChoiceMode(myListView.CHOICE_MODE_SINGLE);
		
		myListAdapter = new ListViewSnoozeSoundListAdapter(myListSound, this, myPath + "databases/");		
		myListView.setAdapter(myListAdapter);
		//
		myListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				VPSnoozeSound sound = new VPSnoozeSound(); 
				sound = myListSound.get(position);

				//arg0.getChildAt(myPositionCurrentOfList).setBackgroundResource(R.color.White);
				myPositionCurrentOfList =  position;
				
				if( !String.valueOf(myListSound.get(position).getVpssId()).isEmpty()){
					myListView.focusableViewAvailable(arg1);
					myListView.setSelection(position);
					
					try {
						onStopSound();
						Thread.sleep(100);						
					} catch (InterruptedException e) {					
						e.printStackTrace();
					};	
					
					onStartSound(myPositionCurrentOfList);
					
					myListView.setItemChecked(myPositionCurrentOfList, true);
					
					myListAdapter.setMyLastSelectedPostition(myPositionCurrentOfList);
				}
				
				
			}
		});
		
		myListView.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	@Override
	protected void onStop() {   
	    super.onStop();
	    if (myPlayer.isPlaying()){
			myPlayer.stop();
			myIbtnPlay.setBackgroundResource(R.raw.play_icon);						
		}	    
	}
	
	public void onStartSound(int position)
	{	
		if (myListAdapter.getCount() > 0)
		{
			if (myPlayer.isPlaying())
			{
				myPositionseek = myPlayer.getCurrentPosition();
				myPlayer.pause();
				myIbtnPlay.setBackgroundResource(android.R.drawable.ic_media_play);
			}
			else
			{						
				if (myPositionseek == 0){	
					try {
						
						if (myPlayer != null)
						{							
							myPlayer.release();
							myPlayer = null;	
						}
						
						myPlayer = new MediaPlayer();
						myPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
						myPlayer.setDataSource(myPath +"sounds/" + myListSound.get(position).getVpssFilePath());
						myPlayer.prepare(); 
						myPlayer.start();
						
						myDuration = myPlayer.getDuration();  
						mySeekBar.setMax(myDuration);
						
						//set filename
						myTvFileName.setText(myListSound.get(position).getVpssFilePath() + "     ");
						
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
						
				}else{					
					myPlayer.seekTo(myPositionseek);			              
					myPlayer.start();
					myPositionseek = 0;					
				}
		
				myIbtnPlay.setBackgroundResource(android.R.drawable.ic_media_pause);
			}	
			
			myListView.setItemChecked(myPositionCurrentOfList, true);
			
			myListAdapter.setMyLastSelectedPostition(myPositionCurrentOfList);
		}
	
	}
	
	public void onStopSound()
	{	
	    if (myPlayer.isPlaying())
	    	myPlayer.stop();    
		    
		myPositionseek = 0;
		myIbtnPlay.setBackgroundResource(android.R.drawable.ic_media_play);			

	}
	
	private class ListViewSnoozeSoundListAdapter extends BaseAdapter {

		public final static String SETTING_SOUND = "com.vinaprime.primeschedule.presentation.SETTING_SOUND";
		private Context myContext;

		private VPSnoozeSound mySound;
		private List<VPSnoozeSound> myListSound;

		private LayoutInflater myInflater;
		private View myListView;
		private TextView myTvPath, myTvSoundSize;
		private RadioButton myRbtnChoose;
		
		private int myLastSelectedPostition;
		
		public ListViewSnoozeSoundListAdapter(List<VPSnoozeSound> _listSound, Context _context, String _path){
		
			myContext = _context;
			
			myListSound = _listSound;
			
			myInflater = (LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			myLastSelectedPostition = -1;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return myListSound.size();
		}

		@Override
		public VPSnoozeSound getItem(int position) {
			// TODO Auto-generated method stub
			return myListSound.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return myListSound.get(position).getVpssId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
				
			convertView = null;
			myListView = null;
			
			final int posTemp = position;
			
			if (convertView == null){
				myListView = new View(myContext);
				myListView = myInflater.inflate(R.layout.activity_vpsnoozesound_list_sub, null);
				
				myTvPath  = (TextView)myListView.findViewById(R.id.tvSoundPath);
				myTvSoundSize = (TextView)myListView.findViewById(R.id.tv_SoundSize);
				
				mySound = new VPSnoozeSound();
				mySound = getItem(position);
				
				myTvPath.setText(mySound.getVpssFilePath());
				myTvSoundSize.setText(Math.round(mySound.getVpssSize()/1024)+" KB");
				
				myRbtnChoose = (RadioButton)myListView.findViewById(R.id.rbtnChoose);
				myRbtnChoose.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Serializable soundReturn = (Serializable)getItem(posTemp);
						
						Intent intent = new Intent();
						intent.putExtra(SOUND_CHOOSE, soundReturn);
						setResult(REQUEST_CODE, intent);
						finish();
					}
				});	
				
				if(position % 2 == 0)
				{
					myListView.setBackgroundResource(R.drawable.background_shape_gray);
					myTvPath.setTextColor(Color.BLACK);
					myTvSoundSize.setTextColor(Color.BLACK);
				}
				else
				{
					myListView.setBackgroundResource(R.drawable.background_shape_green);
					myTvPath.setTextColor(Color.WHITE);
					myTvSoundSize.setTextColor(Color.WHITE);
				}
				
				if(position == myLastSelectedPostition)
				{
					myListView.setBackgroundResource(R.drawable.list_selector_pressed_shape);
					myTvPath.setTextColor(Color.WHITE);
					myTvSoundSize.setTextColor(Color.WHITE);
				}
				
			}
			
			return myListView;
		}
		
		public void setMyLastSelectedPostition(int myLastSelectedPostition) {
			this.myLastSelectedPostition = myLastSelectedPostition;
		}

		public int getMyLastSelectedPostition() {
			return myLastSelectedPostition;
		}

	}
}
